<?php
declare(strict_types=1);

namespace App\Workers;

use App\Models\College;
use App\Services\YikaoCollegeDetailSpiderService;
use GuzzleHttp\Client;
use Monolog\Logger;
use Workerman\Worker;

class YikaoCollegeDetailSpiderWorker
{
    public static function run(Worker $worker, int $limit = 0): void
    {
        $logger = $worker->logger ?? new Logger('院校详情采集Worker');

        // 初始化HTTP客户端
        $httpClient = new Client([
            'timeout' => 30,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            ],
            'proxy' => 'http://127.0.0.1:1080'
        ]);

        // 初始化服务
        $spiderService = new YikaoCollegeDetailSpiderService($httpClient, $logger);

        $worker->onWorkerStart = function(Worker $worker) use ($logger, $spiderService, $limit) {
            $logger->info('========================================');
            $logger->info('院校详情采集Worker启动', [
                'pid' => $worker->id,
                'time' => date('Y-m-d H:i:s'),
                'limit' => $limit
            ]);
            $logger->info('========================================');

            // 获取所有需要采集的院校ID
            $collegeIds = self::getCollegeIds($limit);
            $total = count($collegeIds);
            $logger->info("共获取到 {$total} 个院校需要采集");

            foreach ($collegeIds as $schoolId) {
                try {
                    $logger->info('开始采集院校详情', ['school_id' => $schoolId]);
                    // 获取院校详情数据
                    $collegeData = $spiderService->fetchCollegeDetail($schoolId);
                    if (!$collegeData) {
                        $logger->warning('获取院校详情数据为空', ['school_id' => $schoolId]);
                        continue;
                    }
                    echo "院校名称" . $collegeData['name'] . "\n";
                    // 保存院校详情数据
                    $result = $spiderService->saveCollegeDetail($collegeData);
                    if ($result) {
                        $logger->info('院校详情保存成功', ['school_id' => $schoolId]);
                        echo "采集成功\n";
                    } else {
                        $logger->error('院校详情保存失败', ['school_id' => $schoolId]);
                        echo "采集失败\n";
                    }

                    // 防止请求过于频繁
                    sleep(1);
                } catch (\Exception $e) {
                    $logger->error('院校详情采集异常', [
                        'school_id' => $schoolId,
                        'error' => $e->getMessage(),
                        'trace' => $e->getTraceAsString()
                    ]);
                }
            }

            $logger->info('院校详情采集Worker完成');
            $worker->stop();
        };
    }

    /**
     * 获取所有需要采集的院校ID
     * @param int $limit 限制采集数量
     * @return array
     */
    private static function getCollegeIds(int $limit = 0): array
    {
        // 这里从college表中获取所有院校ID
        // 实际项目中可能需要分批获取或使用游标
        // 这里简化处理，返回一个示例数组
        return College::query()->where('status', 0)->pluck('school_id')->toArray();
    }
}
